/**
 * Created by 功振 on 2016/4/6.
 */

module.controller('ImageDetailController', function ($scope, $cookies, $stateParams, dockerRegisterService, DeleteImageData, PublishImageData, cfpLoadingBar, ROLE,utilService) {
    //$scope.isPrivate = !$scope.isMarket;
    var role = $cookies.get("role");
    if (role == ROLE.OPERATOR) {
        $scope.isOperator = true;
    }
    $scope.ns = $cookies.get("username");
    //$scope.image =  $stateParams.image;
    $scope.image = {
        name: $stateParams.imageName,
        //isMarket: new Boolean($stateParams.isMarket)
        isMarket: $stateParams.isMarket == "true"
    }
    $scope.imageDatas = [];

    dockerRegisterService.getImageInfo($scope.image).then(function(rets){
        //need to create tag list object
        var _lst = [];
        rets.data.results[0].taglist.forEach(function(one){
            var _item = utilService.deepCopyObj(rets.data.results[0]);
            _item.imageversion = one;
            _lst.push(_item);
        })

        $scope.imageDatas = _lst.slice();
    },function( err ){
        if( err && err.data){
            alertify.error(""+err.data ) ;
        }else{
            alertify.error("Request timeout." ) ;
        }
        console.log("[Error]("+err.status+")"+ err.data ) ;
    });

    $scope.$watchCollection('imageDatas', function (newvalue,oldvalue) {
        $scope.datas = newvalue;
    });

    $scope.del = function (data) {

        alertify.confirm("Image Operation","确定删除 "+data.name+':'+data.imageversion+" 镜像?",
            function(){
                DeleteImageData.async(data.name,data.imageversion).then(function (r) {
                    //console.log(( r.data === false )+ JSON.stringify( r )) ;
                    if( r && r.data === true ){
                        var _idx = $scope.imageDatas.indexOf(data);
                        $scope.imageDatas.splice(_idx, 1);
                        alertify.success("删除镜像 ["+data.name+':'+data.imageversion+"] 成功！");
                    }else{
                        alertify.error("删除镜像 ["+data.name+':'+data.imageversion+"] 失败！");
                    }
                }, function (err) {
                    if( !err || err.data === null  ){
                        alertify.error("Request timeout !!") ;
                    }else{
                        alertify.alert("image operate error","删除镜像 ["+data.name+':'+data.imageversion+"] 失败");
                    }
                });
            },
            function(){

            }
        );
    };

    $scope.publish = function(data){

        //alertify.message("发布镜像 ["+data.name+':'+data.imageversion+"] 中...");
        PublishImageData.async({"id":data.name,"tag":data.tag,"imghash":data.hash}).then(function (r) {
            alertify.success("发布镜像 ["+data.name+':'+data.imageversion+"] 成功");
        }, function () {
            alertify.alert("image operate error","发布镜像 ["+data.name+':'+data.imageversion+"] 失败");
        });
    };


});